# -*- coding: utf-8 -*-

from odoo import models, fields, api
from odoo.exceptions import ValidationError


class Calibration(models.Model):
    """设备校准模型"""
    _name = 'device.calibration'
    _description = '设备校准管理'
    _order = 'calibration_date desc, id desc'
    _rec_name = 'display_name'
    _inherit = ['device.permission.mixin']
    
    # 关联设备
    equipment_id = fields.Many2one('device.equipment', '设备', required=True, ondelete='cascade')
    equipment_name = fields.Char('设备名称', related='equipment_id.name', store=True)
    equipment_code = fields.Char('设备编号', related='equipment_id.code', store=True)
    equipment_category = fields.Char('设备类别', related='equipment_id.category_name', store=True)
    equipment_model = fields.Char('设备型号', related='equipment_id.model', store=True)
    
    # 校准基础信息
    calibration_date = fields.Date('校准日期', required=True, default=fields.Date.today)
    calibration_cycle = fields.Integer('校准周期（月）', required=True, default=12)
    next_calibration_date = fields.Date('下次校准日期', compute='_compute_next_calibration_date', store=True)
    internal_number = fields.Char('内部编号', required=True)
    
    # 校准类型
    calibration_type = fields.Selection([
        ('initial', '初次校准'),
        ('periodic', '定期校准'),
        ('maintenance', '维修后校准'),
        ('special', '专项校准')
    ], string='校准类型', default='periodic', required=True)
    
    # 校准状态
    status = fields.Selection([
        ('planned', '计划中'),
        ('ongoing', '进行中'),
        ('qualified', '合格'),
        ('unqualified', '不合格'),
        ('limited', '限制使用'),
        ('cancelled', '已取消')
    ], string='校准状态', default='planned', required=True)
    
    # 校准标准和方法
    calibration_standard = fields.Text('校准标准')
    calibration_method = fields.Text('校准方法')
    measurement_range = fields.Char('测量范围')
    accuracy_requirement = fields.Char('准确度要求')
    
    # 校准结果
    calibration_result = fields.Text('校准结果')
    uncertainty = fields.Char('测量不确定度')
    conclusion = fields.Text('校准结论')
    
    # 校准机构
    calibration_agency = fields.Char('校准机构')
    calibrator = fields.Char('校准员')
    calibrator_certificate = fields.Char('校准员证书号')
    certificate_number = fields.Char('校准证书号')
    
    # 校准环境
    temperature = fields.Char('温度')
    humidity = fields.Char('湿度')
    other_conditions = fields.Text('其他环境条件')
    
    # 标准器信息
    reference_standard = fields.Text('标准器信息')
    
    # 文件附件
    attachment_ids = fields.One2many('ir.attachment', 'res_id', 
                                   domain=[('res_model', '=', 'device.calibration')], 
                                   string='校准附件')
    
    # 附件URL字段 - 存储通过公共上传接口上传的文件URL
    attachment_urls = fields.Text('附件URL列表', help='存储文件URL，多个URL用换行分隔')
    calibration_report_url = fields.Char('校准报告URL', help='校准报告文件的URL')
    certificate_url = fields.Char('证书URL', help='校准证书文件的URL')
    image_urls = fields.Text('现场图片URL', help='校准现场图片的URL，多个URL用换行分隔')
    
    # 显示名称
    display_name = fields.Char('显示名称', compute='_compute_display_name', store=True)
    
    # 创建和修改信息
    create_time = fields.Datetime('创建时间', default=fields.Datetime.now)
    update_time = fields.Datetime('更新时间', default=fields.Datetime.now)
    create_by = fields.Char('创建者')
    update_by = fields.Char('更新者')
    remark = fields.Text('备注')
    
    @api.depends('calibration_date', 'calibration_cycle')
    def _compute_next_calibration_date(self):
        for record in self:
            if record.calibration_date and record.calibration_cycle:
                # 计算下次校准日期
                from dateutil.relativedelta import relativedelta
                record.next_calibration_date = record.calibration_date + relativedelta(months=record.calibration_cycle)
            else:
                record.next_calibration_date = False
    
    @api.depends('equipment_id', 'calibration_date', 'internal_number')
    def _compute_display_name(self):
        for record in self:
            if record.equipment_id and record.calibration_date:
                record.display_name = f"{record.equipment_id.name} - {record.internal_number} ({record.calibration_date})"
            else:
                record.display_name = "新校准记录"
    
    @api.constrains('calibration_cycle')
    def _check_calibration_cycle(self):
        for record in self:
            if record.calibration_cycle <= 0:
                raise ValidationError('校准周期必须大于0个月。')
    
    @api.constrains('internal_number')
    def _check_internal_number_unique(self):
        for record in self:
            if self.search_count([
                ('internal_number', '=', record.internal_number),
                ('equipment_id', '=', record.equipment_id.id),
                ('id', '!=', record.id)
            ]) > 0:
                raise ValidationError(f'该设备的内部编号 {record.internal_number} 已存在。')
    
    @api.model_create_multi
    def create(self, vals_list):
        for vals in vals_list:
            vals['create_time'] = fields.Datetime.now()
            if self.env.user:
                vals['create_by'] = self.env.user.name
        return super().create(vals_list)
    
    def write(self, vals):
        vals['update_time'] = fields.Datetime.now()
        if self.env.user:
            vals['update_by'] = self.env.user.name
        return super().write(vals)
    
    def action_start_calibration(self):
        """开始校准"""
        self.write({'status': 'ongoing'})
    
    def action_qualify_calibration(self):
        """校准合格"""
        self.write({'status': 'qualified'})
    
    def action_disqualify_calibration(self):
        """校准不合格"""
        self.write({'status': 'unqualified'})
    
    def action_limit_calibration(self):
        """限制使用"""
        self.write({'status': 'limited'})
